package com.wedo.mall.widget;

import android.content.Context;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.e.library.http.EApi;
import com.e.library.http.EClient;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.e.library.utils.EDensityUtils;
import com.e.library.utils.EUtils;
import com.e.library.utils.EViewUtils;
import com.wedo.mall.R;
import com.wedo.mall.adapter.AttrAdapter;
import com.wedo.mall.entity.Attr;
import com.wedo.mall.entity.AttrItem;
import com.wedo.mall.entity.Goods;
import com.wedo.mall.entity.GoodsOn;
import com.wedo.mall.fragment.AttrFragment;
import com.wedo.mall.util.WUrl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 选择商品属性
 * @author lxy
 * @time 2017/8/3  14:56
 */
public class AttrWidget {

    private View mWidget;
    @BindView(R.id.iv_img)      ImageView iv_img;
    @BindView(R.id.tv_name)     TextView tv_name;
    @BindView(R.id.tv_price)    TextView tv_price;
    @BindView(R.id.rv_attr)     RecyclerView rv_attr;
    @BindView(R.id.tv_number)   TextView tv_number;
    @BindView(R.id.tv_sku)      TextView tv_sku;
    @BindView(R.id.btn_confirm) Button btn_confirm;

    @BindString(R.string.goods_price) String goods_price;
    @BindString(R.string.goods_stock_only) String goods_stock_only;
    @BindString(R.string.goods_inventory_shortage) String goods_inventory_shortage;

    private Goods goods;
    private Context context;
    private AttrAdapter mAdapter;
    private GoodsOn mSelectedGoods;//所选的商品
    private List<GoodsOn> goodsOns;

    public void init(Context context, Goods goods){
        this.goods = goods;
        this.context = context;
        mWidget = LayoutInflater.from(context).inflate(R.layout.layout_attr,null);
        ButterKnife.bind(this,mWidget);

        display();

        rv_attr.setHasFixedSize(true);
        EViewUtils.vertical(rv_attr);
        mAdapter = new AttrAdapter(context,new ArrayList<Attr>());
        rv_attr.setAdapter(mAdapter);
        mAdapter.setOnAttrChanged(new AttrAdapter.OnAttrChanged() {
            @Override
            public void selected(ArrayMap<Attr, AttrItem > map) {
                onAttrChanged(map);
            }
        });
        sku();
    }

    public View widget(){
        return mWidget;
    }

    public void attach(FrameLayout fl){
        int height = EDensityUtils.dip2px(context,320);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,height);
        params.gravity = Gravity.BOTTOM;
        fl.addView(mWidget,params);
    }

    private void sku(){
        Map<String,String> params = new HashMap<>(2);
        params.put("category_id",goods.agent_category_id);
        params.put("relevance_id",goods.relevance_id);

        EClient.with().post(EApi.GOODS_SKU, params, new EObserver() {
            @Override
            public void successful(EResponse response) {
                List<Attr> list = response.list("attrNameInfo",Attr.class);
                goodsOns = response.list("goodsOn",GoodsOn.class);
                mAdapter.refresh(list);
            }

            @Override
            public void failure(String msg) {
                toast(msg);
            }
        });

    }

    private void onAttrChanged(ArrayMap<Attr,AttrItem> map){
        if (map.size() == mAdapter.getItemCount()){
            Collection<AttrItem> items = map.values();
            StringBuilder idsStr = new StringBuilder();//拼接所选的属性id，如：1-4
            boolean hasMore = false;
            for (AttrItem item:items){
                idsStr.append(hasMore?"-":"");
                idsStr.append(item.id);
                hasMore = true;
            }

            mSelectedGoods = null;
            if (EUtils.isEmpty(goodsOns)){
                display();
                return;
            }

            /**匹配是否有库存*/
            for (GoodsOn goodsOn:goodsOns){
                if (TextUtils.equals(idsStr,goodsOn.skuid)){
                    mSelectedGoods = goodsOn;
                    break;
                }
            }

            display();

        }else {
            mSelectedGoods = null;
            display();
        }

    }

    private void display(){
        if (mSelectedGoods !=null){

            /**显示所选的商品*/
            tv_name.setText(mSelectedGoods.goods_name);
            tv_price.setText(String.format(goods_price,mSelectedGoods.price()));
            String img = WUrl.url(mSelectedGoods.goods_image);
            Glide.with(context).load(img).error(R.drawable.place_holder_goods).placeholder(R.drawable.place_holder_goods).diskCacheStrategy(DiskCacheStrategy.ALL).into(iv_img);
            /**有库存*/
            int sku = mSelectedGoods.surplus;
            if (sku > 0) {
//                btn_confirm.setEnabled(false);
                btn_confirm.setEnabled(true);
                if (sku <10){
                    tv_sku.setText(String.format(goods_stock_only,sku));
                }else {
                    tv_sku.setText(R.string.goods_in_stock);
                }

            } else {
                tv_sku.setText(R.string.goods_sale_out);
                btn_confirm.setEnabled(false);
            }
        }else {
            /**显示默认的商品*/
            tv_sku.setText("");
            btn_confirm.setEnabled(false);
            tv_name.setText(goods.goods_name);
            tv_price.setText(String.format(goods_price,goods.fixPrice()));
            tv_number.setText(String.valueOf(goods.goods_number));
            String img = WUrl.url(goods.goods_image);
            Glide.with(context).load(img).error(R.drawable.place_holder_goods).placeholder(R.drawable.place_holder_goods).diskCacheStrategy(DiskCacheStrategy.ALL).into(iv_img);
        }
    }

    @OnClick(R.id.tv_sub)
    protected void onSubClick(){
        int number = value();
        if (number <=1){
            return;
        }

        number --;
        tv_number.setText(String.valueOf(number));
    }


    @OnClick(R.id.tv_plus)
    protected void onPlusClick(){
        int number = value();
        number++;
        if (mSelectedGoods !=null && number > mSelectedGoods.surplus){
            toastSku();
            return;
        }
        tv_number.setText(String.valueOf(number));
    }

    private int value(){
        String txt = tv_number.getText().toString();
        if(TextUtils.isEmpty(txt)) {
            return 1;
        }
        return Integer.valueOf(txt);
    }

    @OnClick(R.id.btn_confirm)
    protected void onConfirmClick(){
        int number = value();
        if (number > mSelectedGoods.surplus) {
            toastSku();
            return;
        }

        ArrayMap<Attr,AttrItem> map = mAdapter.selected();
        if(mOnSelectedAttr !=null) {
            mOnSelectedAttr.onSelected(mSelectedGoods.id,number,map.values());
        }
    }

    private void toastSku(){
        toast(String.format(goods_inventory_shortage,mSelectedGoods.surplus));
    }

    private void toast(String toast){
        Toast.makeText(context,toast,Toast.LENGTH_SHORT).show();
    }

    private AttrFragment.OnSelectedAttr mOnSelectedAttr;
    public void setOnSelectedAttr(AttrFragment.OnSelectedAttr onSelectedAttr) {
        this.mOnSelectedAttr = onSelectedAttr;
    }
}
